from flask import abort
from flask import request
from flask.ext.classy import FlaskView, route
from marshmallow import ValidationError

from ..schema.error import success, PARAMS_ERROR, CREAT_BRAN_ERROR, LOCAL_BRAN_NOT_EXIST, UPDATA_BRAND_ERROR
from ..schema.resp import brand_schema_list, query_schema, brand_schema
from ..schema.param import  brand_param

from ..services.brand import BrandService

class BrandView(FlaskView):

    #添加品牌
    @route('/', methods=['POST'])
    def create_brand(self):
        if request.data:
            try:
                data ,_ = brand_param.load(request.get_json())
            except   ValidationError  as  ve:
                return PARAMS_ERROR.jsonify(ve)
            brand_name = data.pop('brand_name')
            if not brand_name:
                abort(404)

            describe = data.pop('describe')
            logo =  data.pop('logo')
            brand = BrandService.create_brand(brand_name,describe,logo)

            if brand:
                return success.jsonify()
            else:
                return CREAT_BRAN_ERROR.jsonify()

    #根据品牌名字模糊查询品牌，返回品牌所有属性
    @route('/filter/<brand_name>', methods=['GET'])
    def get_brand(self,brand_name):

        brand = BrandService.get_brand_by_name(brand_name)
        if brand:
            return query_schema.jsonify_with(
                items=brand_schema_list.dump(brand).data
            )
        else:
            return LOCAL_BRAN_NOT_EXIST.jsonify()

    #查询出所有品牌，返回结果集
    @route('/',methods=['GET'])
    def filter_brand(self):
        return query_schema.jsonify_with(
            items=brand_schema_list.dump(BrandService.get_brand_all()).data
        )

    @route('/update',methods=['POST'])
    def update_brand(self):
        data,_ = brand_schema.load(request.get_json())
        id = data.get('id')
        if not id:
            abort(404)
        else:
            brand = BrandService.get_brand_by_id(brand_id=id)
            brand_name = data.get('brand_name')
            describe = data.get('describe')
            logo = data.get('logo')
            status = data.get('status')
            if brand:
                brand_item =  BrandService.update_brand(id=id,brand_name=brand_name,
                                                 describe=describe,logo=logo,status=status)
            else:
                return LOCAL_BRAN_NOT_EXIST.jsonify()
            if brand_item:
                return success.jsonify()
            else:
                UPDATA_BRAND_ERROR.jsonify()
